package internal

import (
	"go.uber.org/zap"
	"gogogo-server/engine/cororpc"
	"gogogo-server/engine/network/codec/msgpack"
	"gogogo-server/logicserver/db"
	"gogogo-server/protocol"
)

func (lg *LetGoGame) registerHandlers() {
	lg.GetServerCoroRPC().RegisterHandler(protocol.MsgEventHelloWorld, helloWorld)
	lg.GetServerCoroRPC().RegisterHandler(protocol.MsgEventLogin, roleLogin)
	lg.GetServerCoroRPC().RegisterHandler(protocol.MsgEventCreateRoom, createRoom)
	lg.GetServerCoroRPC().RegisterHandler(protocol.MsgEventJoinRoom, joinRoom)
}

func helloWorld(arg cororpc.IMessageArg) {
	msg := arg.GetMsg().(*protocol.HelloWorld)
	zap.S().Infof("收到HelloWorld消息:%s, remote:%s", msg.Data, arg.GetAgent().RemoteAddr())
	LocalModule.PushCoroRequest(db.Module, &cororpc.BaseMessageArg{MsgId: protocol.CoroLoadPlayer,
		Msg: "HelloAccount"},
		func(err error, ret any) {
			zap.S().Infof("加载角色回来了, seqId:%d,err:%s, ret:%s", 0, err, ret)
		})
}

func roleLogin(arg cororpc.IMessageArg) {
	msg := arg.GetMsg().(*protocol.LoginArg)
	zap.S().Infof("收到登录消息:%s, remote:%s", msg.Token, arg.GetAgent().RemoteAddr())
	LocalModule.PushCoroRequest(db.Module,
		&cororpc.BaseMessageArg{
			MsgId: protocol.CoroLoadPlayer,
			Msg:   msg.Token,
		},
		func(err error, ret any) {
			zap.S().Infof("加载角色回来了, ,err:%s, ret:%s", err, ret)
			var res protocol.LoginRes
			if err != nil {
				res.Err = err.Error()
			} else {
				res.RoleBasic = ret.(protocol.RoleBasicNode)
			}
			arg.GetAgent().SendMsg(msgpack.BuildMessage(protocol.MsgEventLogin, res))
		})
}

func createRoom(arg cororpc.IMessageArg) {
	ud := arg.GetAgent().GetUserData()
	if nil == ud {
		// 需要登录
		return
	}
	//if nil == r { // 角色找不到
	//return
	//}

	arg.GetAgent().SendMsg(msgpack.BuildMessage(protocol.MsgEventCreateRoom, nil))
}

func joinRoom(arg cororpc.IMessageArg) {

}
